﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using ElementumForever.Interfaces;
using ElementumForever.Enums;
using ElementumForever.Utility;

namespace ElementumForever
{
    public class Camera : ICamera
    {
        Matrix _projectionTransform;

        public Camera()
        {
            _projectionTransform = Matrix.Identity;
            Width = GraphicConstant.WINDOW_WIDTH;
            Height = GraphicConstant.WINDOW_HEIGHT;
            OriginX = Width / 2;
            OriginY = Height / 2;
            Rotation = 0;
            ScaleX = ScaleY = 1;
        }

        public Matrix Projection
        { get { return _projectionTransform; } }

        public Matrix Unprojection
        {
            get {
                float radians = UnitHelper.ToRadians(Rotation);
                Matrix backToOriginTransform = Matrix.CreateTranslation(-X, -Y, 0);
                Matrix rotationTransform = Matrix.CreateRotationZ(-radians);
                Matrix scaleTransform = Matrix.CreateScale(new Vector3(1f / ScaleX, 1f / ScaleY, 0));
                Matrix centerTransform = Matrix.CreateTranslation(OriginX, OriginY, 0);

                Matrix finalTransform;
                finalTransform = backToOriginTransform * scaleTransform * rotationTransform * centerTransform;
                return finalTransform;
            }
        }

        public void OnUpdate(GameTime gameTime)
        {
            float radians = UnitHelper.ToRadians(Rotation);
            Matrix translateToOrigin = Matrix.CreateTranslation(-OriginX, -OriginY, 0);
            Matrix rotationMatrix = Matrix.CreateRotationZ(radians);
            Matrix zoomMatrix = Matrix.CreateScale(new Vector3(ScaleX, ScaleY, 0));
            Matrix translateToOrigin2 = Matrix.CreateTranslation(X, Y, 0);
            _projectionTransform = translateToOrigin * rotationMatrix * zoomMatrix * translateToOrigin2;
            //Console.WriteLine(_cameraTransform);
            //Matrix translateBackToPosition = Matrix.CreateTranslation(world.X, world.Y, 0);
        }
       
        public float OriginX
        { get; set; }

        public float OriginY
        { get; set; }

        public float Rotation
        { get; set; }

        public float ScaleX
        { get; set; }

        public float ScaleY
        { get; set; }

        public float Width
        { get; set; }

        public float Height
        { get; set; }

        public float X
        { get; set; }

        public float Y
        { get; set; }

        public EntityInfo Serialize()
        {
            throw new NotImplementedException();
        }

        public void Build(IsceneBuilder builder, LuaInterface.LuaTable define)
        {
            throw new NotImplementedException();
        }
    }
}
